package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WxPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {

    /***
     *微信下单
     * @param orderId
     * @param money
     * @return
     */
    @Autowired
    private WxPayService wxPayService;

    @GetMapping("/nativePay")
    public Result<Map<String, Integer>> nativePay(@RequestParam("orderId") String orderId, @RequestParam("money") Integer money) {
        Map<String, String> resultMap = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK, "下单成功", resultMap);
    }

    /***
     * 测试回调
     */

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //微信回调接口 黑客发的请求(100万订单,支付成功了)
    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("支付成功回调");
        try {
            //1.拿到这个订单的消息
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);

            //畅购商城的业务逻辑 order payStatus 0 ---> 1
            //1.request的xml
            Map<String, String> huidiaoMap = WXPayUtil.xmlToMap(xml);

            //拿出哪个订单支付成功了
            if (huidiaoMap.get("return_code").equals("SUCCESS") && huidiaoMap.get("result_code").equals("SUCCESS")) {
                String orderId = huidiaoMap.get("out_trade_no");
                //2.重新拿着订单号,问微信查询一下,到底支付成功了没有
                Map<String, String> chaxunMap = wxPayService.queryOrder(orderId);
                if (chaxunMap != null && chaxunMap.get("return_code").equals("SUCCESS") && chaxunMap.get("result_code").equals("SUCCESS")) {
                    //3.往mq发消息 这个订单支付了
                    Map<String, String> payMap = new HashMap();
                    payMap.put("orderId", chaxunMap.get("out_trade_no"));
                    payMap.put("transactionId", chaxunMap.get("transaction_id"));

                    //消息的发送 修改订单状态
                    rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(payMap));

                    //完成双向通信
                    rabbitTemplate.convertAndSend("paynotify", "", chaxunMap.get("out_trade_no"));

                } else {
                    //输出错误原因
                    System.out.println(chaxunMap.get("renter_msg"));
                    System.out.println(chaxunMap.get("err_code_des"));
                }
            } else {
                //输出错误原因
                System.out.println(huidiaoMap.get("renter_msg"));
                System.out.println(huidiaoMap.get("err_code_des"));
            }

            //2.商户处理后同步返回给微信参数
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        } catch (Exception e) {
            //logger.error
            e.printStackTrace();
        }
    }

    /***
     * 查询微信订单
     * @param orderId
     * @return
     */
    @GetMapping("/query/{orderId}")
    public Result<Map<String, String>> queryOrder(@PathVariable String orderId) {
        Map<String, String> map = wxPayService.queryOrder(orderId);
        return new Result(true, StatusCode.OK, "查询订单成功", map);
    }

    /***
     * 关闭微信订单
     * @param orderId
     * @return
     */
    @PutMapping("/close/{orderId}")
    public Result<Map<String, String>> closeOrder(@PathVariable String orderId) {
        Map<String, String> map = wxPayService.closeOrder(orderId);
        return new Result(true, StatusCode.OK, "关闭订单成功", map);
    }
}
